HttpRequest.is_ajax() is deprecated starting with version 3.1.
I want to return html if the page is requested from a browser and as JsonResponse if called from javascript or programmatically.
I am seeking guidance on how to do that.
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.is_ajax
Check HTTP_X_REQUESTED_WITH header
def sample_view(request):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
From the Release Notes of 3.1
The
HttpRequest.is_ajax()method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the newHttpRequest.accepts()method if your code depends on the client Accept HTTP header.
Funny thing -- the quoted deprecation blurb only gets you halfway there. There's no indication of how you "use the new HttpRequest.accepts method" to replace HttpRequest.is_ajax -- not in the deprecation text, nor the documentation, nor the release notes.
So, here it is: if request.accepts("application/json")
(At least that's what worked for me.)
Instead of:
if request.is_ajax():
Helped me:
if request.headers.get('x-requested-with') == 'XMLHttpRequest':